/*
 * General main file for Towerhack Server
 */

#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#include "resources.h"
#include "lobby.h"
#include "game.h"
#include "setup.h"
#include "bailout.h"
#include "network.h"

int quit = 0;
int global_state;

void update_state ()
{
	switch (global_state) {
		case STATE_LOBBY:
			lobby_update();
			network_update();
			break;
		case STATE_GAME:
			game_update();
			network_update();
			break;
		default:
			bailout ("s", "unexpected game state fail");
	}
}

void change_state (int new_state) {
	switch (global_state) {
		case STATE_UNDEFINED:
			break;
		case STATE_LOBBY:
			// cleanup lobby?
			break;
		case STATE_GAME:
			game_cleanup();
			break;
		default:
			assert(0);
	}
	global_state = new_state;
	switch (new_state) {
		case STATE_LOBBY:
			lobby_init();
			break;
		case STATE_GAME:
			game_init();
			break;
		default:
			assert(0);
	}
}

void main_loop ()
{
	ticks = 0;
	while (!quit) {
		update_state();
		ticks--;
		while (ticks <= 0) {
			rest(1);
		}
	}
}

int main (int argc, char* argv[])
{
	quit = 0;
	global_state = STATE_UNDEFINED;

	// Timer from allegro? FIXME
	allegro_init();
	install_timer();
	install_int_ex(timer, BPS_TO_TIMER(FPS));
	
	load_data (); /* from files */
	change_state (STATE_LOBBY); // initial default state

	main_loop ();

	cleanup ();
	fprintf(stderr, "Towerhack Server shutdown\n");
	return EXIT_SUCCESS;
}
END_OF_MAIN()
